package com.shengsheng.expschedule.service.expschedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shengsheng.expschedule.service.expschedule.entity.Semester;
import com.shengsheng.expschedule.service.expschedule.mapper.SemesterMapper;
import com.shengsheng.expschedule.service.expschedule.service.SemesterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 学期表 服务实现类
 * </p>
 *
 * @author yuan
 * @since 2021-09-29
 */
@Service
public class SemesterServiceImpl extends ServiceImpl<SemesterMapper, Semester> implements SemesterService {


    @Override
    public Date getOriginDate(String semesterId) {

        QueryWrapper<Semester> semesterQueryWrapper = new QueryWrapper<>();
        semesterQueryWrapper.eq("id", semesterId)
                .select("semester_origin_date");
        return this.getOne(semesterQueryWrapper).getSemesterOriginDate();
    }

    @Override
    public Long CalcBetweenDays(String semesterId, Date newDate) {

        QueryWrapper<Semester> semesterQueryWrapper = new QueryWrapper<>();
        semesterQueryWrapper.eq("id", semesterId)
                .select("semester_origin_date");
        Semester semester = baseMapper.selectOne(semesterQueryWrapper);
        return (newDate.getTime() - semester.getSemesterOriginDate().getTime()) / (60 * 60 * 24 * 1000);
    }

    @Override
    public List<Semester> getSemesterListOrderByOriginDate() {

        QueryWrapper<Semester> semesterQueryWrapper = new QueryWrapper<>();
        semesterQueryWrapper.orderByDesc("semester_origin_date");
        return this.list(semesterQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean setCurrentSemesterById(String id) {

        Semester semester = baseMapper.selectById(id);
        if (semester == null) return false;
        // 获得原来的主学期
        QueryWrapper<Semester> semesterQueryWrapper = new QueryWrapper<>();
        semesterQueryWrapper.eq("is_current_semester", true);
        Semester selectOne = baseMapper.selectOne(semesterQueryWrapper);
        // 设置原来的不为主学期
        selectOne.setIsCurrentSemester(false);
        baseMapper.updateById(selectOne);
        semester.setIsCurrentSemester(true);
        return this.updateById(semester);
    }

}
